import Vue from 'vue'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Config from '../config/index'
import Token from "../auth/token"
import request from "@/itsoftUI/utils/request";
import qs from "qs"

export default {
    init: function (Router) {
        NProgress.configure({
            showSpinner: false
        }) // NProgress Configuration
        Router.beforeEach((to, from, next) => {
            // start progress bar
            NProgress.start()
            console.log(to)
            if (to.path === "/login") {
                if (Token.isLogin()) {
                    next('/home')
                } else {
                    if (to.query.userinfo) {
                        //第三方登录过来的传来用户信息，要做静默登录获取授权
                        let userInfo = encodeURI(to.query.userinfo)
                        let clientId = Config.clientId
                        let schoolCode = Config.schoolCode
                        let schoolName = Config.schoolName
                        let timestamp = Token.getTimestamp()
                        const data = {
                            userInfo,
                            clientId,
                            timestamp,
                            schoolCode,
                            schoolName
                        }
                        request({
                            url: Config.serviceUrl + '/auth/login/auto',
                            method: 'post',
                            data: qs.stringify(data)
                        }).then(res => {
                            //保存token
                            Vue.prototype.$itsoftUI.saveTokenKey(res.data)
                            //重新获取
                            localStorage.removeItem("USER_INFO")
                            let toPath = localStorage.getItem("topath")
                            let redirect = localStorage.getItem("redirect")
                            if (toPath && redirect) {
                                window.location.href = redirect + toPath
                            } else {
                                if (!toPath) {
                                    toPath = '/home'
                                }
                                next(toPath)
                            }
                        }).catch(err => {
                            next("/error")
                        })
                    } else {
                        //存储返回路径
                        localStorage.removeItem("redirect")
                        localStorage.removeItem("topath")
                        if (to.query.redirect) {
                            localStorage.setItem("redirect", to.query.redirect.toString())
                        }
                        if (to.query.topath) {
                            localStorage.setItem("topath", to.query.topath.toString())
                        }
                        if (Config.casUrl) {
                            // window.location.href = Config.casUrl + "/login?redirect=" + Config.loginUrl + "/login"
                            window.location.href = Config.casUrl + "/login"
                            // window.location.href = Config.casLogoutUrl


                        } else {
                            next()
                        }
                    }
                }
            } else {
                //获取路由配置是否验权
                let auth = to.meta.Auth;
                if (Token.isLogin()) {
                    try {
                        Token.getUserInfo().then(res => {
                            if (res.password === '0') {
                                if (to.path === "/initpsw") {
                                    next()
                                } else {
                                    next('/initpsw')
                                }
                            } else {
                                console.log(to)
                                if (to.path === "/loginlocal") {
                                    next('/home')
                                } else if (to.path === "/initpsw") {
                                    next('/home')
                                } else if (to.path === '/servicesCatalogue') {
                                    //禁言用户
                                    Token.isForbidden().then((res) => {
                                        if (res) {
                                            next()
                                        } else {
                                            if (from.path === '/banned') {
                                                NProgress.done()
                                            } else {
                                                next('/banned')
                                            }
                                        }
                                    });
                                } else {
                                    next()
                                }
                            }
                        })
                    } catch (e) {
                        next("/error")
                    }

                } else {
                    //未登录
                    //初始化本地用户数据
                    localStorage.removeItem("USER_INFO")
                    //登录跳转
                    if (auth) {
                        if (Config.localUrl === Config.loginUrl) {
                            next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
                            NProgress.done()
                        } else {
                            let goTo = Config.loginUrl + "/login?redirect=" + Config.localUrl + "&topath=" + to.path
                            window.location.href = goTo
                        }
                    } else {
                        next()
                    }
                }
            }
        })
        Router.afterEach(() => {
            // finish progress bar
            NProgress.done()
            window.scrollTo(0, 0)
        })
    }
}